﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

namespace GrayParrot.Web.Formly
{
    public class ExpressionPropertiesConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            bool r = typeof(IEnumerable).IsAssignableFrom(objectType) &&
                               !typeof(string).IsAssignableFrom(objectType);

            //bool r = objectType == typeof(FieldItem);
            return r;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //FieldItem fi = (FieldItem)value;
            IEnumerable<FieldItem> collectionObj = value as IEnumerable<FieldItem>;

            foreach (FieldItem fi in collectionObj)
            {
                if ((fi.TemplateOptions == null) && ((fi.Childs != null) && (fi.Childs.Count() > 0)))
                {
                    if ((fi.Childs != null) && (fi.Childs.Count > 0))
                    {
                        foreach (FieldItem item in fi.Childs)
                        {
                            JObject jo1 = DoWork(item);
                            jo1.WriteTo(writer);
                        }
                    }
                }
                else
                {
                    JObject jo1 = DoWork(fi);
                    jo1.WriteTo(writer);
                }
            }
        }

        private JObject DoWork(FieldItem item)
        {
            JObject retValue = JObject.FromObject(item);

            if ((item.ExpressionProperties != null) && (item.ExpressionProperties.Items.Count() > 0))
            {
                ExpressionProperties m_temp = item.ExpressionProperties;

                // Create a JObject from the document, respecting existing JSON attribs
                JObject joEP = JObject.FromObject(m_temp);

                foreach (ExpressionProperty ep in m_temp.Items)
                {
                    joEP.Add(ep.PropertyName, JToken.FromObject(ep.ExpressionCallback));
                }

                retValue["expressionProperties"] = joEP;
            }

            return retValue;
        }
    }
}
